package com.example.play_car

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer

import androidx.activity.viewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout

class PlayCarFragment : Fragment() {

    // 帖子列表控件
    private lateinit var recyclerView: RecyclerView
    // Tab控件（热门、帖子、关注）
    private lateinit var tabLayout: TabLayout
    // 搜索输入框
    private lateinit var searchEdit: EditText
    // 当前分类（2=热门，0=帖子）
    private var currentCategory = 2
    // 是否只看关注
    private var ifFocus = 0
    // 分页参数
    private var pageNum = 1
    private var pageSize = 10
    // ViewModel实例
    private val viewModel by viewModels<PlayCarViewModel>()
    // 适配器实例
    private val adapter = PostAdapter()
    private lateinit var swipeRefresh: androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    private var isLoadingMore = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        val inflate = inflater.inflate(R.layout.fragment_play_car, container, false)
        // 初始化控件
        recyclerView = inflate.findViewById(R.id.recyclerView)
        tabLayout = inflate.findViewById(R.id.tabLayout)
        searchEdit = inflate.findViewById(R.id.searchEdit)
        swipeRefresh = inflate.findViewById(R.id.swipeRefresh)

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter

        // 下拉刷新
        swipeRefresh.setOnRefreshListener {
            pageNum = 1
            loadPosts()
        }

        // 上拉加载更多
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(rv, dx, dy)
                val layoutManager = rv.layoutManager as LinearLayoutManager
                val lastVisible = layoutManager.findLastVisibleItemPosition()
                val total = adapter.itemCount
                if (!isLoadingMore && lastVisible >= total - 2 && dy > 0) {
                    isLoadingMore = true
                    pageNum++
                    loadPosts()
                }
            }
        })

        // 监听帖子数据变化，刷新列表
        viewModel.posts.observe(viewLifecycleOwner, Observer {
            if (pageNum == 1) {
                adapter.submitList(it)
            } else {
                // 分页追加
                val newList = adapter.currentList.toMutableList()
                newList.addAll(it)
                adapter.submitList(newList)
            }
            swipeRefresh.isRefreshing = false
            isLoadingMore = false
        })
        // 监听错误信息，弹出提示
        viewModel.errorMsg.observe(viewLifecycleOwner, Observer {
            swipeRefresh.isRefreshing = false
            isLoadingMore = false
            Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
        })

        // Tab切换监听
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                when (tab.position) {
                    0 -> { currentCategory = 2; ifFocus = 0 } // 热门
                    1 -> { currentCategory = 0; ifFocus = 0 } // 帖子
                    2 -> { currentCategory = 0; ifFocus = 1 } // 关注
                }
                pageNum = 1
                loadPosts()
            }
            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })

        // 搜索输入监听
        searchEdit.setOnEditorActionListener { _, _, _ ->
            pageNum = 1
            loadPosts(searchEdit.text.toString())
            true
        }

        // 添加Tab
        tabLayout.removeAllTabs()
        tabLayout.addTab(tabLayout.newTab().setText("热门"))
        tabLayout.addTab(tabLayout.newTab().setText("帖子"))
        tabLayout.addTab(tabLayout.newTab().setText("资讯"))
        tabLayout.addTab(tabLayout.newTab().setText("关注"))

        // 首次加载
        loadPosts()

        return inflate
    }
    /**
     * 调用ViewModel加载帖子数据
     * @param keyword 搜索关键字
     */
    private fun loadPosts(keyword: String = "") {
        viewModel.loadPosts(currentCategory, ifFocus, keyword, pageNum, pageSize)
    }
}